<template>
  <div>
    <h3 style="text-align: center;font-size: 16px;color: #7a7a7a">{{ chartTitle }}</h3>
    <el-select class="flex-container"  v-model="selectedSeries" @change="updateLegend" >
      <el-option value="All">All</el-option>
      <el-option v-for="(data, index) in seriesData" :key="index" :value="data.name">
        {{ data.name }}
      </el-option>
    </el-select>
    <div ref="chart" :style="{ width: chartWidth, height: chartHeight }"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'ResponseTimeChart',
  props: {
    chartTitle: {
      type: String,
      default: '平均响应时间'
    },
    chartUnit: {
      type: String,
      default: '单位(毫秒)'
    },
    chartWidth: {
      type: String,
      default: '400px'
    },
    chartHeight: {
      type: String,
      default: '300px'
    },
    xData: {
      type: Array,
      required: true
    },
    seriesData: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      selectedSeries: 'All', // 默认选择全部
    };
  },

  mounted() {
    this.$nextTick(() => {
      this.initChart();
    });
  },

  methods: {
    initChart() {
      const chart = echarts.init(this.$refs.chart);
      this.chartInstance = chart; // 保存实例以便后续更新
      this.updateChart(); // 初始化图表
    },

    updateLegend() {
      this.updateChart(); // 更新图表
    },

    updateChart() {
      const chart = this.chartInstance;

      const series = this.seriesData.map(data => ({
        name: data.name,
        type: 'line',
        data: this.selectedSeries === 'All' || this.selectedSeries === data.name ? data.values : [],
        showSymbol: false,
      }));

      const option = {
        // title: {
        //   text: this.chartTitle,
        //   x: 'center',
        //   textStyle: {
        //     fontSize: 16,
        //     fontWeight: 'bold',
        //   },
        // },
        tooltip: {
          trigger: 'axis',
        },
        xAxis: {
          type: 'category',
          data: this.xData,
          axisLabel: {
            rotate: 45,
            color: 'black',
          },
          axisLine: {
            lineStyle: {
              color: 'rgb(251, 212, 55)',
              width: 2
            }
          },
        },
        yAxis: {
          name: this.chartUnit,
          type: 'value',
        },
        series: series
      };

      chart.setOption(option);
    },
  }
};
</script>

<style scoped>

.flex-container{
  margin-left: 16px;
  width: 100px;
  margin-bottom: -20px;

}
</style>
